/* eslint-disable react-hooks/exhaustive-deps */
import React from 'react'
import {
  Card,
  Upload,
  Radio,
  Breadcrumb,
  Form,
  Input,
  Button,
  message,
  Modal,
  Space
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useHistory, useParams } from 'react-router-dom'
import Channel from '@/components/channel'
import style from './index.module.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import {
  saveArticle,
  getOneArticle,
  editArticle
} from '@/store/actions/article'
import { useDispatch } from 'react-redux'

export default function Publish () {
  const dispatch = useDispatch()
  const history = useHistory()
  const formRef = React.useRef(null)
  const { id } = useParams()
  // 编辑数据回填
  React.useEffect(
    () => {
      const getArticleInfo = async () => {
        if (id) {
          const res = await dispatch(getOneArticle(id))
          console.log(res, 'id54612156312')
          // 表单的回显
          formRef.current.setFieldsValue({
            ...res,
            type: res.cover.type
          })
          // 图片的回显
          setType(res.cover.type)
          const list = res.cover.images.map((item) => {
            return {
              url: item
            }
          })
          console.log(list, 123456789456123)
          setFileList(list)
          fileRef.current = list
        }
      }
      getArticleInfo()
    },
    ['id']
  )
  // 图片上传
  const baseURL = 'http://geek.itheima.net/v1_0/'
  // 通过封面数量控制图片数量(通过ref共享数据来控制)
  // 1.添加ref
  const [fileList, setFileList] = React.useState([])
  const fileRef = React.useRef(fileList)
  const onChange = ({ fileList }) => {
    setFileList(fileList)
    // 2.保存图片数量
    fileRef.current = fileList
    // 上传图片时更新校验
    formRef.current.validateFields(['type'])
  }
  // 封面数量
  const [type, setType] = React.useState(1)
  const onTypeChange = (e) => {
    const count = e.target.value
    setType(count)
    // 3.通过封面数量和保存在ref中的数量来动态设置图片显示数量
    setFileList(fileRef.current.slice(0, count))
  }
  // 组装接口所需提交数据
  const PublishData = (values) => {
    // 说明：如果选择 3 图，图片数量必须是 3 张，否则，后端会当做单图处理
    //      后端根据上传图片数量，来识别是单图或三图
    if (values.type === 3 && fileList.length !== 3)
      return message.warning('封面数量不为3张')

    const images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })

    const { type, ...rest } = values
    const data = {
      ...rest,
      // 注意：接口会按照上传图片数量来决定单图 或 三图
      cover: {
        type,
        images
      }
    }
    return data
  }
  // 封装提交功能
  const Publish = async (values, draft, type) => {
    const data = PublishData(values)
    try {
      if (id) {
        // 修改
        await dispatch(editArticle({ ...data, id }, draft))
        message.success(`${type}发布成功!`, 1, () => {
          history.push('/home/list')
        })
      } else {
        await dispatch(saveArticle(data, draft))
        message.success(`${type}发布成功!`, 1, () => {
          history.push('/home/list')
        })
      }
    } catch (err) {
      message.error(`${type}发布失败!`)
    }
  }
  // 提交事件
  const onFinish = async (values) => {
    Publish(values, false, '文章')
  }
  // 存入草稿
  const addDraft = async () => {
    const values = await formRef.current.validateFields()
    Publish(values, true, '草稿')
  }
  // 图片预览
  const [isVisible, setIsVisible] = React.useState(false)
  const [preview, setPreview] = React.useState('')
  const onPreview = (file) => {
    console.log(file)
    setIsVisible(true)
    setPreview(file.url || file.response.data.url)
  }
  return (
    <div className={style.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form
          initialValues={{ type: 1, content: '' }}
          labelCol={{ span: 4 }}
          ref={formRef}
          onFinish={onFinish}
          wrapperCol={{ span: 20 }}
          size="large">
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '标题不能为空'
              }
            ]}>
            <Input placeholder="请输入文章的标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '频道不能为空'
              }
            ]}>
            <Channel />
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator (_, value) {
                  if (fileList.length !== value) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                }
              }
            ]}>
            <Radio.Group value={type} onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={0}>无图</Radio>
              <Radio value={3}>三图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            {/* fileList: 控制上传的图片,做回填 */}
            <Upload
              listType="picture-card"
              fileList={fileList}
              name="image"
              action={`${baseURL}upload`}
              onChange={onChange}
              maxCount={type}
              onPreview={onPreview}>
              {fileList.length < type && <PlusOutlined />}
            </Upload>
            <Modal
              width={800}
              title="图片预览"
              visible={isVisible}
              footer={null}
              onCancel={() => setIsVisible(false)}>
              <div style={{ textAlign: 'center' }}>
                <img src={preview} style={{ width: 600 }} alt="" />
              </div>
            </Modal>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '内容不能为空'
              }
            ]}>
            <ReactQuill />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button htmlType="submit" type="primary">
                {id ? '编辑' : '发布'}文章
              </Button>
              <Button onClick={addDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
